import React, { useState } from 'react'
import { StyleSheet, Image } from 'react-native'
import { user } from '@/mock/mockjs'

import { ThemedText } from '@/components/ThemedText'
import { ThemedView } from '@/components/ThemedView'
import useResponsize from '@/rem/rem'
import {
  Tab,
  Text,
  TabView,
  Input,
  Button,
  CheckBox,
  Dialog,
} from '@rneui/themed'
import { Link, useRouter } from 'expo-router'
// import { Camera, CameraType } from 'expo-camera';

export default function LoginScreen() {
  const { w, h, fs } = useResponsize()
  const router = useRouter()
  const styles = StyleSheet.create({
    container: {
      height: h(820),
      backgroundColor: '#f3f3f3',
    },
    image: {
      height: h(200),
    },
    img: {
      width: w(100),
      height: h(100),
      marginLeft: '37%',
      marginTop: '10%',
    },
    welcome: {
      height: h(100),
      lineHeight: h(100),
      fontSize: fs(26),
      fontWeight: 'bold',
      textAlign: 'center',
      backgroundColor: '#fff',
    },
    inputView: {
      height: h(450),
      lineHeight: h(450),
      fontSize: fs(20),
      textAlign: 'center',
      backgroundColor: '#fff',
      margin: 10,
    },
    InputText: {
      fontSize: fs(20),
      padding: 10,
    },
    checked: {
      fontSize: fs(20),
      margin: 10,
    },
    containers: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    camera: {
      width: '100%',
      height: '100%',
    },
    face: {
      position: 'absolute',
      borderWidth: 2,
      borderColor: 'red',
    },
  })
  //tabs的切换状态
  const [index, setIndex] = useState(0)
  //用户协议
  const [checked, setChecked] = React.useState(false)
  const toggleCheckbox = () => setChecked(!checked)
  //用户名和密码
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const Login = () => {
    if (!checked) {
      alert('请先同意协议')
    } else {
      if (username === '' || password === '') {
        alert('请输入用户名和密码')
      } else {
        if (
          username === user.role.username &&
          password === user.role.password
        ) {
          alert('登录成功')
          router.push('/(tabs)')
        } else {
          alert('用户名或密码错误')
        }
      }
    }
  }
  //手机号登录
  const [tel, setTel] = useState('')
  const [ma, setMa] = useState('')
  const [code, setCode] = useState('')
  //用户协议
  const [checkedd, setCheckedd] = React.useState(false)
  const toggleCheckboxx = () => setCheckedd(!checked)
  //获取验证码
  const getCode = () => {
    const randomNumber = Math.floor(Math.random() * 900000) + 100000 // 生成6位随机数
    setMa(randomNumber.toString())
  }

  let countdown = 60 // 倒计时时间，单位秒
  const [disabled, setDisabled] = useState(false) // 是否禁用按钮
  const [text, setText] = useState('获取验证码') // 按钮文本
  const CodeTel = () => {
    if (!checkedd) {
      alert('请先同意协议')
    } else {
      if (tel === '') {
        alert('请输入手机号')
      } else {
        // 添加手机号正则表达式校验
        const phoneRegex =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (!phoneRegex.test(tel)) {
          alert('请输入有效的手机号')
        } else {
          getCode()
          if (countdown === 60) {
            countdown = 60 // 重置倒计时
            setText(`还剩 ${countdown} 秒`)
            setDisabled(true)
            const interval = setInterval(() => {
              countdown--
              setText(`还剩 ${countdown} 秒`)
              if (countdown <= 0) {
                clearInterval(interval)
                setText('获取验证码')
                setDisabled(false)
                countdown = 60 // 重置倒计时
              }
            }, 1000)
          }
        }
      }
    }
  }
  //验证码登录
  const loging = () => {
    if (!checkedd) {
      alert('请先同意协议')
    } else {
      if (tel === '' || code === '') {
        alert('请输入手机号和验证码')
      } else {
        // 添加手机号正则表达式校验
        const phoneRegex =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (!phoneRegex.test(tel)) {
          alert('请输入有效的手机号')
        } else {
          // 这里可以添加验证验证码的逻辑
          if (code === ma) {
            // 假设这是验证验证码的逻辑
            alert('登录成功')
            router.push('/(tabs)')
          } else {
            alert('手机号或验证码错误')
          }
        }
      }
    }
  }
  //获取不到验证码
  const [visible1, setVisible1] = useState(false)
  const toggleDialog1 = () => {
    setVisible1(!visible1)
  }
  return (
    <ThemedView style={styles.container}>
      <ThemedView style={styles.image}>
        <Image
          source={{
            uri: 'https://ts3.cn.mm.bing.net/th?id=ODL.e5473b4a2eefbef03bef9024cb75644e&w=110&h=110&c=6&rs=1&qlt=90&o=6&dpr=1.3&pid=23.1',
          }}
          style={styles.img}
        />
      </ThemedView>
      <ThemedView style={styles.inputView}>
        <Tab
          value={index}
          onChange={(e) => setIndex(e)}
          indicatorStyle={{
            backgroundColor: '#000',
            height: 4,
          }}
        >
          <Tab.Item title="用户密码" titleStyle={{ fontSize: fs(12) }} />
          <Tab.Item title="手机号登录" titleStyle={{ fontSize: fs(12) }} />
        </Tab>
        <TabView value={index} onChange={setIndex} animationType="spring">
          <TabView.Item
            style={{
              backgroundColor: '#fff',
              width: '100%',
              height: h(520),
            }}
          >
            <ThemedView>
              <ThemedView style={{ marginTop: h(20) }}>
                <ThemedText style={styles.InputText}>Username</ThemedText>
                <Input
                  placeholder="请输入用户名"
                  onChange={(ev) => setUsername(ev.nativeEvent.text)}
                />
              </ThemedView>
              <ThemedView>
                <ThemedText style={styles.InputText}>Password</ThemedText>
                <Input
                  secureTextEntry={true}
                  placeholder="请输入密码"
                  onChange={(ev) => setPassword(ev.nativeEvent.text)}
                />
              </ThemedView>
              <Button onPress={() => Login()} title="确认登录" />
              <CheckBox
                checked={checked}
                title="同意宠物市场《用户协议》和《隐私政策》"
                onPress={toggleCheckbox}
                iconType="material-community"
                checkedIcon="checkbox-outline"
                uncheckedIcon={'checkbox-blank-outline'}
              />
            </ThemedView>
          </TabView.Item>
          <TabView.Item
            style={{
              backgroundColor: '#fff',
              width: '100%',
              height: h(520),
            }}
          >
            <ThemedView style={{ marginTop: h(20) }}>
              <ThemedView>
                <ThemedText style={styles.InputText}>Tel</ThemedText>
                <Input
                  placeholder="请输入手机号"
                  onChange={(ev) => setTel(ev.nativeEvent.text)}
                />
              </ThemedView>
              <ThemedView>
                <ThemedText style={styles.InputText}>Code</ThemedText>
                <ThemedView style={{ display: 'flex', flexDirection: 'row' }}>
                  <Input
                    secureTextEntry={true}
                    placeholder="请输入验证码"
                    containerStyle={{ width: w(200) }}
                    onChange={(ev) => setCode(ev.nativeEvent.text)}
                  />
                  <Button
                    title={text}
                    buttonStyle={{
                      backgroundColor: 'black',
                      borderWidth: 2,
                      borderColor: 'white',
                      borderRadius: 30,
                    }}
                    containerStyle={{
                      width: 200,
                      height: 40,
                    }}
                    titleStyle={{ fontWeight: 'bold' }}
                    disabled={disabled}
                    onPress={() => CodeTel()}
                  />
                </ThemedView>
              </ThemedView>
              <ThemedText
                style={{ margin: h(10), textAlign: 'right' }}
                onPress={() => toggleDialog1()}
              >
                获取不到验证码？
              </ThemedText>
              <Dialog isVisible={visible1} onBackdropPress={toggleDialog1}>
                <Dialog.Title title="收不到验证码？" />
                <Text style={{fontSize:fs(14)}}>1.请确认当前手机号是否填写正确</Text>
                <Text style={{fontSize:fs(14)}}>2.请查看短信是否被手机安全软件拦截</Text>
                <Text style={{fontSize:fs(14)}}>3.手机信号较弱,请稍等片刻</Text>
                <Text style={{fontSize:fs(14)}}>4.手机可能欠费时间过长</Text>
              </Dialog>
              <Button onPress={() => loging()} title="手机号登录" />
              <CheckBox
                checked={checkedd}
                title="同意宠物市场《用户协议》和《隐私政策》"
                onPress={toggleCheckboxx}
                iconType="material-community"
                checkedIcon="checkbox-outline"
                uncheckedIcon={'checkbox-blank-outline'}
              />
              <ThemedText>获取到的验证码是：{ma}</ThemedText>
            </ThemedView>
          </TabView.Item>
        </TabView>
      </ThemedView>
    </ThemedView>
  )
}
